package com.sky.service.impl;


import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.OrderDetail;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WorkspaceService workspaceService;
    /**
     *营业额统计
     */
    @Override
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {
        //存放每天日期的列表
        List<LocalDate> dateList = new ArrayList<>();
        //存放每天营业额的列表
        List<Double> turnoverList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)){
            //对当前天数+1存入list中，直到结束日期
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        //遍历日期列表，查询出每天的营业额
        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            //将起始时间，结束时间，订单已完成，封装为map
            HashMap map = new HashMap();
            map.put("begin",beginTime);
            map.put("end",endTime);
            map.put("status", Orders.COMPLETED);
            //根据传递的参数查询当天的营业额总数
            Double amount = orderMapper.sumByMap(map);
            //特判，为null不符合业务逻辑
            amount = amount == null? 0.0 : amount;
            turnoverList.add(amount);
        }
        return TurnoverReportVO
                .builder()
                .dateList(StringUtils.join(dateList, ","))
                .turnoverList(StringUtils.join(turnoverList,","))
                .build();

    }

    /**
     * 用户统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {
        //每天的日期的列表
        List<LocalDate> dateList = new ArrayList<>();
        //截止到当天用户总数的列表
        List<Integer> totalUserList = new ArrayList<>();
        //每日新增的用户列表
        List<Integer> newUserList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)){
            //对当前天数+1存入list中，直到结束日期
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            //将起始时间，结束时间，封装为map
            HashMap map = new HashMap();
            map.put("end",endTime);
            //根据传递的参数查询截止到当天的用户总数
            //select count(id) from user where creatime < ?
            Integer totalUser = userMapper.sumByMap(map);
            totalUserList.add(totalUser);
            //新增的用户数量
            //select count(id) from user where creatime > ? and create_time < ?
            map.put("begin",beginTime);
            Integer newUser = userMapper.sumByMap(map);
            newUserList.add(newUser);
        }

        return UserReportVO
                .builder()
                .newUserList(StringUtils.join(newUserList,","))
                .totalUserList(StringUtils.join(totalUserList,","))
                .dateList(StringUtils.join(dateList,","))
                .build();
    }

    /**
     * 订单统计
     */
    @Override
    public OrderReportVO orderStatistics(LocalDate begin, LocalDate end) {
        //每天的日期的列表
        List<LocalDate> dateList = new ArrayList<>();
        //订单数列表
        List<Integer> orderCountList = new ArrayList<>();
        //有效订单数列表
        List<Integer> validOrderCountList = new ArrayList<>();
        while (!begin.equals(end)){
            //对当前天数+1存入list中，直到结束日期
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            //获取每天的订单数
            Integer orderCount = getOrderCount(beginTime,endTime,null);
            orderCountList.add(orderCount);
            //获取每天的有效订单数
            Integer validCount = getOrderCount(beginTime,endTime,Orders.COMPLETED);
            validOrderCountList.add(validCount);
        }
        //列表合并获取订单总数
        Integer totalOrderCount = orderCountList.stream().reduce(Integer::sum).get();
        //列表合并获取有效订单数
        Integer validOrderCount = validOrderCountList.stream().reduce(Integer::sum).get();
        //订单完成率
        Double orderCompletionRate = 0.0;
        if (totalOrderCount!=0){
            orderCompletionRate = validOrderCount.doubleValue()/totalOrderCount;
        }
        return OrderReportVO
                .builder()
                .dateList(StringUtils.join(dateList,","))
                .validOrderCount(validOrderCount)
                .totalOrderCount(totalOrderCount)
                .validOrderCountList(StringUtils.join(validOrderCountList,","))
                .orderCountList(StringUtils.join(orderCountList,","))
                .orderCompletionRate(orderCompletionRate)
                .build();
    }

    public Integer getOrderCount(LocalDateTime begin,LocalDateTime end,Integer status){
        //动态获取订单数量
        //将起始时间，结束时间，封装为map
        HashMap map = new HashMap();
        map.put("begin",begin);
        map.put("end",end);
        map.put("status",status);
        return orderMapper.getOrderCount(map);
    }

    /**
     * 销量排名统计
     */
    @Override
    public SalesTop10ReportVO top10(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        HashMap map = new HashMap();
        map.put("begin",beginTime);
        map.put("end",endTime);
        //查询出销量前十的菜品名称和销量
        List<GoodsSalesDTO> salesTop10 = orderMapper.getTop10(map);
        //商品名称列表
        List<String> nameList = salesTop10.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        //销量列表
        List<Integer> numberList = salesTop10.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());
        return SalesTop10ReportVO
                .builder()
                .nameList(StringUtils.join(nameList,","))
                .numberList(StringUtils.join(numberList,","))
                .build();
    }

    /**
     * 导出运营数据报表
     */
    @Override
    public void export(HttpServletResponse response) {
        //通过输入流获取对应路径下的模板Excel
        InputStream excelPath = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        try {
            XSSFWorkbook excel = new XSSFWorkbook(excelPath);
            //获取sheet页
            XSSFSheet sheet = excel.getSheet("Sheet1");
            //查询对应的数据写入Excel的对应单元格中
            LocalDate begin = LocalDate.now().minusDays(30);
            LocalDate end = LocalDate.now().minusDays(1);
            //获取近一个月的时间
            LocalDateTime dateBegin = LocalDateTime.of(begin, LocalTime.MIN);
            LocalDateTime dateEnd = LocalDateTime.of(end, LocalTime.MAX);
            //获取第二行的第二个拼上近一个月的时间
            XSSFRow row = sheet.getRow(1);
            row.getCell(1).setCellValue("时间："+begin+"至"+end);
            //获取概览数据
            BusinessDataVO businessData = workspaceService.getBusinessData(dateBegin, dateEnd);
            row = sheet.getRow(3);
            row.getCell(2).setCellValue(businessData.getTurnover());
            row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
            row.getCell(6).setCellValue(businessData.getNewUsers());
            row = sheet.getRow(4);
            row.getCell(2).setCellValue(businessData.getValidOrderCount());
            row.getCell(4).setCellValue(businessData.getUnitPrice());
            //填充数据
            //定义详细数据的插入起始行
            for (int i = 0; i < 30; i++) {
                //获取每天的起始和终止时间
                LocalDate beginTime = begin.plusDays(i);
                dateBegin = LocalDateTime.of(beginTime, LocalTime.MIN);
                dateEnd = LocalDateTime.of(beginTime, LocalTime.MAX);
                row = sheet.getRow(7+i);
                businessData = workspaceService.getBusinessData(dateBegin, dateEnd);
                row.getCell(1).setCellValue(String.valueOf(beginTime));
                row.getCell(2).setCellValue(businessData.getTurnover());
                row.getCell(3).setCellValue(businessData.getValidOrderCount());
                row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessData.getUnitPrice());
                row.getCell(6).setCellValue(businessData.getNewUsers());
            }
            //使用输出流将Excel文件下载到客户端浏览器
            ServletOutputStream outputStream = response.getOutputStream();
            excel.write(outputStream);
            //关闭资源
            excel.close();
            excelPath.close();
            outputStream.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
